<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <!--<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">-->
    <link rel="stylesheet" type="text/css" href="css/common.css">
    <link rel="stylesheet" type="text/css" href="css/main.css">
    <script src="js/jquery-2.2.4.min.js"></script>
    <script src="js/flexible.js"></script>
    <title>错题反馈</title>
</head>

<body>
    <div class="body-wrap">
        <form name="feedback-form">
            <div class="body_main">
                <div class="wrong-type">
                    <h3 class="wrong-title">错题类型<span>（必选）</span>
                        <p class="wrong-note wrong-note1">请选择错题类型</p>
                    </h3>
                    <ul class="clearfix type-list">
                        <li>题干内容有误</li>
                        <li>答案有误</li>
                        <li>选项内容错误</li>
                        <li>图片无法查看</li>
                        <li>解析有误</li>
                        <li>题型有误</li>
                        <li>其他</li>
                    </ul>
                </div>

                <div class="wrong-describe">
                    <h3 class="wrong-title">错题描述<span>（必选）</span>
                        <p class="wrong-note wrong-note2">请输入错题描述（不超过250个字）</p>
                    </h3>
                    <div class="clearfix describe_div">
                        <textarea id="describeText" placeholder="请输入错题描述" maxlength="250"></textarea>
                        <span class="wordsNum">0/250</span>
                    </div>
                </div>

                <div class="wrong-file">
                    <h3 class="wrong-title">附件<p class="wrong-note wrong-note3">文件大小不能大于10M</p>
                    </h3>
                    <div class="upload clearfix">
                        <!-- <div class="upload-img"><img src="images/bg.png"><span class="delete"></span></div> -->

                        <div class="add-btn">
                            <input type="file" name="file" id="imgUpload" accept="image/*">
                        </div>
                    </div>
                </div>
            </div>

            <div class="contact-box" style="height:0;overflow:hidden;">
                <div class="contact-div" style="background:#f2f2f2;">
                    <label class="user-accout">用户账号</label>
                    <input name="feedName" id="feedName" type="text" readonly style="background:#f2f2f2;">
                    <!-- <span class="input-note input-note1"></span> -->
                </div>
                <!-- <div class="contact-div">
                    <label>联系电话</label>
                    <input name="phoneNumber" id="phoneNumber" type="text" placeholder="请输入联系电话">
                    <span class="input-note input-note2">请输入有效的联系电话</span>
                </div> -->
            </div>

            <div class="footer">
                <button class="submit-btn" type="button">提交</button>
            </div>
        </form>
    </div>

    <!-- 提示 -->
    <div class="edit-note">
        <div class="editNote-main">
            <div class="note-text">
                上传成功！
            </div>
            <!-- <div class="note-btn">
                <button>放弃</button>
                <button class="continue">继续</button>
            </div> -->
        </div>
    </div>
</body>

</html>

<script>
    $(function () {
        $('.type-list li').click(function () {
            $(this).toggleClass('selected');
        })
        // $('.continue').click(function () {
        //     $('.edit-note').hide();
        // })
        // $('#phoneNumber').on('input', function () {
        //     if (!/^1[34578]\d{9}$/.test($('#phoneNumber').val())) {
        //         $('.input-note2').show();
        //     } else {
        //         $('.input-note2').hide();
        //     }
        // })
        $('.upload').on('click', '.delete', function () {
            $(this).parent().remove();
        })

        //封装一个限制字数方法
        var checkStrLengths = function (str, maxLength) {
            var maxLength = maxLength;
            var result = 0;
            if (str && str.length > maxLength) {
                result = maxLength;
            } else {
                result = str.length;
            }
            return result;
        }
        //监听输入
        $("#describeText").on('input propertychange', function () {

            //获取输入内容
            var userDesc = $(this).val();

            //判断字数
            var len;
            if (userDesc) {
                len = checkStrLengths(userDesc, 250);
                $('.wrong-note2').hide();
            } else {
                len = 0
                $('.wrong-note2').show();
            }

            //显示字数
            $(".wordsNum").html(len + '/250');
        });

        //敏感词过滤
        $.get('words/dirty1.json').success(function (content) {
            var keywords = content.data;
            $("textarea").on('input', function () {
                _filter_method($(this));
            });

            function _filter_method(obj) {
                //获取文本输入框中的内容
                var value = $(obj).val();
                console.log(value)
                //遍历敏感词数组
                for (var i = 0; i < keywords.length; i++) {
                    //全局替换
                    //判断内容中是否包括敏感词
                    if (value.indexOf(keywords[i]) != -1) {
                        var reg = new RegExp(keywords[i], "g");
                        var str = ''
                        for (var j = 0; j < keywords[i].length; j++) {
                            str += "*"
                        }
                        var result = value.replace(reg, str);
                        console.log(result)
                        $(obj).val(result);
                    }
                }
            }
        })

        // $('#feedName').val(getQueryString('feedbackUserName') ? getQueryString('feedbackUserName') : '1');

        function getQueryString(name) {
            var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
            var r = window.location.search.substr(1).match(reg);
            if (r != null) {
                return decodeURI(r[2]);
            }
            return null;
        }
        // if (getQueryString('chrSource') == 8) {
        //     $('.user-accout').text('工具箱编号')
        // } else {
        //     $('.user-accout').text('用户账号')
        // }
        // console.log(getQueryString('chrSource'))
        var xhrOnProgress = function (fun) {
            xhrOnProgress.onprogress = fun; //绑定监听
            //使用闭包实现监听绑
            return function () {
                //通过$.ajaxSettings.xhr();获得XMLHttpRequest对象
                var xhr = $.ajaxSettings.xhr();
                //判断监听函数是否为函数
                if (typeof xhrOnProgress.onprogress !== 'function')
                    return xhr;
                //如果有监听函数并且xhr对象支持绑定时就把监听函数绑定上去
                if (xhrOnProgress.onprogress && xhr.upload) {
                    xhr.upload.onprogress = xhrOnProgress.onprogress;
                }
                return xhr;
            }
        }
        $('#imgUpload').change(function (event) {
            $('.submit-btn').attr('disabled', true);
            $('.submit-btn').addClass('gray');
            var fileType = document.getElementById('imgUpload').files[0].name.toLocaleLowerCase();
            console.log(fileType)
            if (!/.(gif|jpg|jpeg|png|GIF|JPG|bmp)$/.test(fileType)) {
                $('.wrong-note3').text('只能上传图片文件')
                $('.wrong-note3').show();
                return false;
            }
            var fileSize = document.getElementById('imgUpload').files[0].size / (1024 * 1024)
            if (fileSize > 10) {
                $('.wrong-note3').text('文件大小不能大于10M')
                $('.wrong-note3').show();
                return false;
            }
            $('.wrong-note3').hide();
            var fileObj = document.getElementById('imgUpload').files[0];
            var formFile = new FormData();
            formFile.append('file', fileObj);
            var reader = new FileReader();
            reader.readAsDataURL(fileObj);
            //监听文件读取结束后事件
            reader.onloadend = function (e) {
                var htmlStr = '<div class="upload-img"><div class="progress"></div><img src="' + e.target.result + '"><span class="delete" style="display:none;"></span></div>';
                $('.add-btn').eq(0).before(htmlStr);
            }
            $('.add-btn').hide()
            $.ajax({
                url: "http://rp-api.bosafe.com/api/app/plupload/doUploadFastImg?name=" + fileObj.name,
                data: formFile,
                type: "Post",
                dataType: "json",
                cache: false,
                contentType: false,
                processData: false,
                xhr: xhrOnProgress(function (e) {
                    var percent = e.loaded * 100 / e.total;
                    $('.progress').eq($('.progress').length - 1).text(percent.toFixed(2) + '%')
                    console.log(percent);
                }),
                success: function (data) {
                    $('#imgUpload').val('')
                    $('.progress').eq($('.progress').length - 1).hide()
                    $('.delete').eq($('.delete').length - 1).show()
                    if ($('.upload-img').length < 5) {
                        $('.add-btn').show()
                    }
                    $('.upload-img').eq($('.upload-img').length - 1).attr('data-id', data.result.fileId)
                    $('.upload-img').eq($('.upload-img').length - 1).attr('data-name', data.result.fileName)
                    $('.submit-btn').attr('disabled', false);
                    $('.submit-btn').removeClass('gray');
                },
                error: function (data) {
                    alert(data.msg)
                }
            })
        });

        $('.submit-btn').click(function () {
            if (!$('.selected').length) {
                $('.wrong-note1').show();
                return false;
            } else if ($('#describeText').val() === '') {
                $('.wrong-note1').hide();
                $('.wrong-note2').show();
                return false;
            }
            $('.wrong-note2').hide();
            var type = [];
            for (let i = 0; i < $('.selected').length; i++) {
                // console.log($('.selected').eq(i).index()+1)
                type.push($('.selected').eq(i).index() + 1)
            }
            var imgIds = []
            for (let i = 0; i < $('.upload-img').length; i++) {
                imgIds.push({
                    'fileId': $('.upload-img').eq(i).attr('data-id'),
                    'fileName': $('.upload-img').eq(i).attr('data-name')
                })
            }

            var param = {
                "intQuestionId": getQueryString('intQuestionId') ? getQueryString('intQuestionId') : 1,
                "varCauseList": type,
                "varContent": $('#describeText').val(),
                "varFileInfo": JSON.stringify(imgIds),
                "intPlatformId": getQueryString('intPlatformId') ? getQueryString('intPlatformId') : 1,
                "varPlatformName": getQueryString('varPlatformName') ? getQueryString('varPlatformName') : '1',
                "companyId": getQueryString('companyId') ? getQueryString('companyId') : '1',
                "companyName": getQueryString('companyName') ? getQueryString('companyName') : '1',
                "chrSource": getQueryString('chrSource') ? getQueryString('chrSource') : '8',
                "feedbackUserId": getQueryString('feedbackUserId') ? getQueryString('feedbackUserId') : '1',
                "feedbackUserName": getQueryString('feedbackUserName') ? getQueryString('feedbackUserName') : '1'
            }
            $.ajax({
                type: "POST",
                url: "http://rp-api.bosafe.com/api/app/exQuestionFeedback/save",
                data: JSON.stringify(param),
                /*dataType : 'JSON',*/
                contentType: "application/json;charset=utf-8",
                success: function (data) {
                    if (data.code == 0) {
                        $('.edit-note').show().delay(1000).hide(0);
                        $('.type-list li').removeClass('selected');
                        $('#describeText').val('');
                        $('.upload .upload-img').remove();

                        // $('#feedName').val('');
                        // $('#phoneNumber').val('');
                        // setTimeout(function(){
                        //     window.location.reload()
                        // },3000)


                        //关闭当前页面
                        function f_close() {
                            if (typeof (WeixinJSBridge) != "undefined") {
                                WeixinJSBridge.call('closeWindow');
                            } else {
                                if (navigator.userAgent.indexOf("MSIE") > 0) {
                                    if (navigator.userAgent.indexOf("MSIE 6.0") > 0) {
                                        window.opener = null; window.close();
                                    } else {
                                        window.open('', '_top'); window.top.close();
                                    }
                                } else if (navigator.userAgent.indexOf("Firefox") > 0) {
                                    window.location.href = 'about:blank ';
                                    //window.history.go(-2);  
                                } else {
                                    window.opener = null;
                                    window.open('', '_self', '');
                                    window.close();
                                }
                                var userAgent = navigator.userAgent;
                                if (userAgent.indexOf("Firefox") != -1 || userAgent.indexOf("Chrome") != -1) {
                                    window.location.href = "about:blank";
                                } else if (userAgent.indexOf('Android') > -1 || userAgent.indexOf('Linux') > -1) {
                                    window.opener = null; window.open('about:blank', '_self', '').close();
                                } else {
                                    window.opener = null;
                                    window.open("about:blank", "_self");
                                    window.close();
                                }
                            }
                        }
                        setTimeout(function () {
                            f_close();
                        }, 1000)
                    } else {
                        $('.note-text').text(data.msg)
                        $('.edit-note').show().delay(2000).hide(0);
                    }
                },
                error: function (data) {
                    alert(data.msg)
                }
            });
        })
    })
</script>